package com.wzh.project.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
 * 序列化反序列化工具类
 * @author wzh
 *
 */
public class BinaryTransferUtils {
	private static final Logger logger=LogManager.getLogger(BinaryTransferUtils.class);
	/**
	 * 字节数组转化为bean对象
	 * @param obj
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 * @throws Exception
	 */
	public static Object transferByteArrayToObject(Object obj){
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream((byte[])obj);  
		Object oRet = null;
		try {
			ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream);
			oRet = inputStream.readObject();
		} catch (Exception e) {
			logger.debug("反序列化错误！",e);
		}
		return oRet;
	}

	/**
	 * bean对象转化为字节数组
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static byte[] transferToBinaryByteArray(Object message){
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
	    ObjectOutputStream outputStream = null;
		try {
			outputStream = new ObjectOutputStream(byteArrayOutputStream);
			outputStream.writeObject(message);
		} catch (IOException e) {
			logger.debug("二进制序列化错误！",e);
		}  
	    byte[] data= byteArrayOutputStream.toByteArray();
		return data;
	}
}
